<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="物流产品名称" :labelCol="{xs: { span: 24 },sm: { span: 8 }}" :wrapperCol="wrapperCol">
              <j-ellipsis :value="model.name" :length="15"></j-ellipsis>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="物流渠道" :labelCol="{xs: { span: 24 },sm: { span: 8 }}" :wrapperCol="wrapperCol">
              <j-ellipsis :value="model.channelName" :length="13"></j-ellipsis>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="成本价方案" :labelCol="{xs: { span: 24 },sm: { span: 8 }}" :wrapperCol="wrapperCol">
              <j-ellipsis :value="model.costPriceId_dictText" :length="13"></j-ellipsis>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="产品代码" :labelCol="{xs: { span: 24 },sm: { span: 8 }}" :wrapperCol="wrapperCol">
              <j-ellipsis :value="model.code" :length="15"></j-ellipsis>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="成本价版本" :labelCol="{xs: { span: 24 },sm: { span: 8 }}" :wrapperCol="wrapperCol" prop="costPriceId" :class="{active: model.upCostPriceId ? true : false}">
              <j-search-select-tag ref="versionRef" placeholder="请选择成本价版本" v-model="model.costPriceId" :dict="selectCode" @change="versionChange" @click.native="handleClick" v-if="pageType === 'historyQuotation'"></j-search-select-tag>
              <j-search-select-tag ref="versionRef" placeholder="请选择成本价版本" v-model="model.costPriceId" @change="versionChange" @click.native="handleClick" v-else></j-search-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="报价生效时间" :labelCol="{xs: { span: 24 },sm: { span: 8 }}" :wrapperCol="wrapperCol" v-if="pageType === 'historyQuotation'">
              <j-date placeholder="请选择生效时间"  v-model="model.effectBeginTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" disabled />
            </a-form-model-item>
            <a-form-model-item label="报价生效时间" :labelCol="{xs: { span: 24 },sm: { span: 8 }}" :wrapperCol="wrapperCol" prop="effectBeginTime" v-else>
              <j-date placeholder="请选择生效时间"  v-model="model.effectBeginTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled-date="disabledDate" :disabled-time="disabledTime" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <div class="table-operator" style="margin-top: 10px;">
          <a-button type="primary" @click="handleBatchCost" :disabled="!model.costPriceId">批量费用</a-button>
          <a-button type="primary" icon="download" @click="handleExportXls('物流成本价详情', '', {costPriceId: model.costPriceId})" :disabled="!model.costPriceId">导出价格</a-button>
          <a-upload name="file" :data="{costPriceId: model.costPriceId}" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
            <a-button type="primary" icon="import" :disabled="!model.costPriceId">导入价格</a-button>
          </a-upload>
        </div>
        <j-editable-table
          :ref="refKeys[0]"
          :loading="logisticsCostPriceDetailTable.loading"
          :columns="logisticsCostPriceDetailTable.columns"
          :dataSource="logisticsCostPriceDetailTable.dataSource"
          :maxHeight="300"
          :rowNumber="true"
          :rowSelection="true"
          @valueChange="handleValueChange"
        />
      </a-form-model>
    </j-form-container>
    <logistics-product-form-modal ref="modalForm" @ok="modalFormOk"></logistics-product-form-modal>
  </a-spin>
</template>

<script>
  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import LogisticsProductFormModal from './LogisticsProductFormModal'
  import moment from 'moment'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'

  export default {
    name: 'LogisticsDefaultPriceForm',
    mixins: [JEditableTableModelMixin, JeecgListMixin],
    components: {
      LogisticsProductFormModal
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          costPriceId: [
            { required: true, message: '请选择成本价版本!'},
          ],
          effectBeginTime: [
            { required: true, message: '请选择报价生效时间!'},
            { validator: this.validEffectBeginTime }
          ]
        },
        url: {
          edit: "/logistics/product/logisticsProduct/changePrice",
          queryDetailByMainId: "/logistics/product/logisticsProduct/queryDetailByMainId",
          exportTemplateXlsUrl: "/logistics/product/hzLogisticsProductDetail/exportTemplate",
          exportXlsUrl: "/logistics/product/hzLogisticsProductDetail/exportExcel",
          importExcelUrl: "logistics/product/hzLogisticsProductDetail/importExcel",
          queryLatestVersion: "/logistics/product/logisticsProduct/queryLatestVersion",
          queryPresetsPriceDetail: "/logistics/product/logisticsProduct/queryPresetsPriceDetail",
          queryAllVersion: "/logistics/costPrice/logisticsCostPrice/queryAllVersion"
        },
        refKeys: ['logisticsCostPriceDetail', ],
        tableKeys:['logisticsCostPriceDetail', ],
        activeKey: 'logisticsCostPriceDetail',
        logisticsCostPriceDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '收费分区',
              key: 'classifyId',
              type: FormTypes.select,
              width:"100px",
              dictCode:"hz_logistics_partition_classify,name,id,logistics",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '计费类型',
              key: 'chargeType',
              type: FormTypes.select,
              dictCode:"logistics_charge_type",
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '开始重量段（KG）',
              key: 'startWeight',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '结束重量段（KG）',
              key: 'endWeight',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '最低计费重（KG）',
              key: 'minChargeWeight',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '',
              defaultValue:'',
              disabled: true
            },
            {
              title: '计费单重（KG）',
              key: 'chargeWeight',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            // {
            //   title: '价格值',
            //   key: 'price',
            //   type: FormTypes.inputNumber,
            //   width:"90px",
            //   placeholder: '请输入${title}',
            //   defaultValue:'',
            //   disabled: true
            // },
            // {
            //   title: '挂号费',
            //   key: 'registerFee',
            //   type: FormTypes.inputNumber,
            //   width:"90px",
            //   placeholder: '请输入${title}',
            //   defaultValue:'',
            //   disabled: true
            // },
            {
              title: '公斤费',
              key: 'kiloFee',
              type: FormTypes.inputNumber,
              width:"90px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, pattern: /^[0-9]+(\.[0-9]+)?$/, message: '${title}不能小于0' }]
            },
            {
              title: '处理费',
              key: 'processFee',
              type: FormTypes.inputNumber,
              width:"90px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, pattern: /^[0-9]+(\.[0-9]+)?$/, message: '${title}不能小于0'}]
            },
          ]
        },
        editProductDetails: [],
        disableMixinCreated: true,
        typeTitle_: '',
        columns: [],
        lastTime: moment(),
        pageType: ''
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
      selectCode(){
        if(!this.model.costPriceCode) return;
        return `hz_logistics_cost_price,version,id,logistics,code='${this.model.costPriceCode}'`;
      }
    },
    created () {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      test(){
        console.log(JSON.stringify(this.model));
      },
      addBefore(){
        this.logisticsCostPriceDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        if (this.model.id) {
          //获取成本价版本
          this.getQueryAllVersion();
          //获取最新版本详情
          this.getQueryLatestVersion();
          // 获取子表单
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.queryDetailByMainId, params, this.logisticsCostPriceDetailTable, (res) => {
            // 拷贝提交数据
            this.editProductDetails = res.result;
          })
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
        return new Promise((resolve,reject)=>{
          Promise.all([
          ]).then(() => {
            resolve(allValues)
          }).catch(e => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
        })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues){
        let productDetails = [...allValues.tablesValue[0].values];
        if(this.typeTitle_ != '导入'){
          //将table中的costPriceDetailId置为id，id置为null
          productDetails = productDetails.map(item => {
            if(!item.costPriceDetailId){
              return {
                ...item,
                costPriceDetailId: item.id,
                id: null
              }
            }else{
              //新增中导入的数据不用重置
              return item;
            }
          })
        }
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          productDetails,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      handleBatchCost(){
        let ref = this.refKeys[0];
        if(this.$refs[ref]){
          let currentSelection = this.$refs[ref].getSelection();
          if(!currentSelection.length){
            this.$message.warning('请选择数据!');
            return;
          }
          this.$refs.modalForm.add();
          this.$refs.modalForm.title = "批量费用设置";
          this.$refs.modalForm.disableSubmit = false;
        }
      },
      modalFormOk(model){
        let ref = this.refKeys[0];
        if(this.$refs[ref]){
          debugger;
          let currentSelection = this.$refs[ref].getSelection();
          this.logisticsCostPriceDetailTable.dataSource = this.editProductDetails.map(item => {
            if(currentSelection.indexOf(item.id) > -1){
              return {
                ...item,
                kiloFee: model.kiloFee,
                processFee: model.processFee
              }
            }else{
              return item;
            }
          })
          this.editProductDetails = this.editProductDetails.map(item => {
            if(currentSelection.indexOf(item.id) > -1){
              return {
                ...item,
                kiloFee: model.kiloFee,
                processFee: model.processFee
              }
            }else{
              return item;
            }
          })
        }
      },
      handleOk_(){
        // 历史报价中的编辑要接口改为
        if(this.pageType === 'historyQuotation'){
          this.url.edit = '/logistics/product/logisticsProduct/edit';
        }
        this.handleOk();
      },
      handleValueChange({ row }){
        this.editProductDetails = this.editProductDetails.map(item => {
          if(item.id === row.id){
            return {
              ...item,
              kiloFee: row.kiloFee,
              processFee: row.processFee
            }
          }else{
            return item
          }
        })
      },
      handleImportExcel(info){
        this.loading = true;
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          this.loading = false;
          if (info.file.response.success) {
            // this.$message.success(`${info.file.name} 文件上传成功`);
            if (info.file.response.code === 201) {
              let { message, result: { msg, fileUrl, fileName } } = info.file.response
              this.$warning({
                title: message,
                content: (<div>
                    <span>{msg}</span><br/>
                    <span>具体详情请 <a href={fileUrl} target="_blank" download={fileName}>点击下载</a> </span>
                  </div>
                )
              })
            } else {
              this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
              //更新表单
              this.logisticsCostPriceDetailTable.dataSource = info.file.response.result.dataList;
              this.editProductDetails = info.file.response.result.dataList;
              this.typeTitle_ = '导入';
            }
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`);
          }
        } else if (info.file.status === 'error') {
          this.loading = false;
          if (info.file.response.status === 500) {
            let data = info.file.response
            const token = Vue.ls.get(ACCESS_TOKEN)
            if (token && data.message.includes("Token失效")) {
              this.$error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                  store.dispatch('Logout').then(() => {
                    Vue.ls.remove(ACCESS_TOKEN)
                    window.location.reload();
                  })
                }
              })
            }
          } else {
            this.$message.error(`文件上传失败: ${info.file.msg} `);
          }
        }
      },
      getQueryLatestVersion(){
        getAction(this.url.queryLatestVersion, { code: this.model.code }).then((res) => {
          if(res.success){
            let lastTime = res.result && res.result.effectBeginTime;
            // 如果最新版本晚于当前时间，则取最新版版本(下一秒)为校验时间
            if(moment(moment(lastTime).format('YYYY-MM-DD HH:mm:ss')).isAfter(moment(moment().format('YYYY-MM-DD HH:mm:ss')))){
              lastTime = moment(lastTime).add(1, 'seconds');
              this.lastTime = lastTime;
            }
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      disabledDate(current){
        // 禁用今天之前的日期
        return current && current < moment(this.lastTime).subtract(1, 'days').endOf('day');
      },
      disabledTime(current){
        let hourList = Array.from({ length: 24 }, (_, index) => index);
        let minutesList = Array.from({ length: 60 }, (_, index) => index);
        let secondsList = Array.from({ length: 60 }, (_, index) => index);
        // 1.选择时间晚于当前(天)
        if(moment(moment(current).format('YYYY-MM-DD')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD')))){
          return {
            disabledHours: () => [],
            disabledMinutes: () => [],
            disabledSeconds: () => [],
          };
        }else if(moment(moment(current).format('YYYY-MM-DD')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD')))){
          //3.编辑返参早于当前
          return {
            disabledHours: () => hourList,
            disabledMinutes: () => minutesList,
            disabledSeconds: () => secondsList,
          };
        }
        // 2.选择时间等于当前(天)
        let currentHourList = [], currentminutesList = [], currentsecondsList = [];
        if(moment(current).format('YYYY-MM-DD') === moment(this.lastTime).format('YYYY-MM-DD')){
          // 选择的时间为限制时间之后
          currentHourList = hourList.filter(item => item < moment(this.lastTime).format('HH'));
          // 2.选择时间等于当前(时)
          if(moment(current).format('YYYY-MM-DD HH') === moment(this.lastTime).format('YYYY-MM-DD HH')){
            // 选择的时间为限制时间之后
            currentminutesList = minutesList.filter(item => item < moment(this.lastTime).format('mm'));
            // 2.选择时间等于当前(分)
            if(moment(current).format('YYYY-MM-DD HH:mm') === moment(this.lastTime).format('YYYY-MM-DD HH:mm')){
              currentsecondsList = secondsList.filter(item => item < moment(this.lastTime).format('ss'));
            }else if(moment(moment(current).format('YYYY-MM-DD HH:mm')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm')))){
              // 选择时间晚于当前(分)
              currentsecondsList = [];
            }else if(moment(moment(current).format('YYYY-MM-DD HH:mm')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm')))){
              // 选择时间早于当前(分)
              currentsecondsList = secondsList;
            }
          }else if(moment(moment(current).format('YYYY-MM-DD HH')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD HH')))){
            // 选择时间晚于当前(时)
            currentminutesList = [];
            currentsecondsList = [];
          }else if(moment(moment(current).format('YYYY-MM-DD HH')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH')))){
            // 选择时间早于当前(时)
            currentminutesList = minutesList;
            currentsecondsList = secondsList;
          }
          return {
            disabledHours: () => currentHourList,
            disabledMinutes: () => currentminutesList,
            disabledSeconds: () => currentsecondsList,
          };
        }
      },
      validEffectBeginTime(rule, value, callback){
        if(!value){
          callback('请选择生效时间!');
        }else{
          if(moment(moment(value).format('YYYY-MM-DD HH:mm:ss')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm:ss')))){
            callback('生效时间需晚于最新版本时间或系统时间!');
          }else{
            callback();
          }
        }
      },
      versionChange(){
        // 加载子表数据
        let params = {
          ...this.model,
          productId: this.model.id,
        }
        this.requestSubTableData(this.url.queryPresetsPriceDetail, params, this.logisticsCostPriceDetailTable, (res) => {
          this.editProductDetails = res.result;
        })
      },
      handleClick(){
        // 成本价版本下拉数据添加更新标识(个性化展示，不在组件中体现)
        if(!this.model.upCostPriceId) return;
        this.$nextTick(() => {
          let dom = document.querySelector('.ant-select-dropdown');
          if(!dom) return;
          let options = this.$refs.versionRef.getCurrentDictOptions();
          let index = options.findIndex(item => item.value === this.model.upCostPriceId);
          if(document.querySelectorAll('.ant-select-dropdown li')){
            document.querySelectorAll('.ant-select-dropdown li').forEach(dom => {
              dom.classList.remove('active_');
            })
            if(document.querySelectorAll('.ant-select-dropdown li')[index]){
              document.querySelectorAll('.ant-select-dropdown li')[index].classList.add('active_');
              document.querySelectorAll('.ant-select-dropdown li')[index].addEventListener('mouseover', function(){
                setTimeout(() => {
                  document.querySelectorAll('.ant-select-dropdown li')[index].classList.add('active_');
                }, 0)
              })
              document.querySelectorAll('.ant-select-dropdown li')[index].addEventListener('mouseout', function(){
                setTimeout(() => {
                  document.querySelectorAll('.ant-select-dropdown li')[index].classList.add('active_');
                }, 0)
              })
            }
          }
        })
      },
      getQueryAllVersion(){
        this.$refs.versionRef.setCurrentDictOptions([]);
        getAction(this.url.queryAllVersion, {costPriceCode: this.model.costPriceCode}).then((res) => {
          if(res.success){
            let options = res.result.map(item => {
              return {
                value: item.id,
                text: item.version
              }
            })
            this.$refs.versionRef.setCurrentDictOptions(options);
          }else{
            this.$message.warning(res.message);
          }
        })
      }
    }
  }
</script>

<style scoped>
/deep/.active, /deep/.active_{
  position: relative;
  &::after{
    content: '';
    display: block;
    width: 5px;
    height: 5px;
    border-radius: 50%;
    background-color: #ff6700;
    position: absolute;
    top: 9px;
    left: 80px;
  }
}
/deep/.active_{
  &::after{
    left: auto;
    right: 10px !important;
  }
}
</style>